<?php

namespace App\Listeners;

use App\Exceptions\API\APIException;
use Dingo\Api\Event\ResponseWasMorphed;
use Dingo\Api\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class AddPaginationHeaderToResponse
{
    /**
     * Handle the event.
     *
     * @param  ResponseWasMorphed  $event
     * @return void
     */
    public function handle(ResponseWasMorphed $event)
    {
        if (!is_array($event->content)) {
            return;
        }

        $this->setXTotalCount($event);
        $this->setLink($event);

        if (isset($event->content['meta'])) {
            unset($event->content['meta']);
        }
        $event->response->headers->set('Access-Control-Allow-Origin', '*');

    }

    /**
     * @param ResponseWasMorphed $event
     */
    private function setXTotalCount(ResponseWasMorphed $event)
    {
        if (isset($event->content['meta']['pagination']['total'])) {
            $event->response->headers->set('X-Total-Count', $event->content['meta']['pagination']['total']);
        }
    }

    /**
     * @param ResponseWasMorphed $event
     */
    private function setLink(ResponseWasMorphed $event)
    {
        if (isset($event->content['meta']['pagination']['links'])) {
            $links = $event->content['meta']['pagination']['links'];
            $linksConfig = [];
            if (isset($links['first'])) {
                $linksConfig[] = $this->generateLinkString($links['first'], 'first');
            }
            if (isset($links['previous'])) {
                $linksConfig[] = $this->generateLinkString($links['previous'], 'prev');
            }
            if (isset($links['next'])) {
                $linksConfig[] = $this->generateLinkString($links['next'], 'next');
            }
            if (isset($links['last'])) {
                $linksConfig[] = $this->generateLinkString($links['last'], 'last');
            }
            if (!empty($linksConfig)) {
                $event->response->headers->set('Link', implode(', ', $linksConfig));
            }
        }
    }

    /**
     * @param $url
     * @param $rel
     * @return string
     */
    private function generateLinkString($url, $rel)
    {
        return "<{$url}>; rel=\"{$rel}\"";
    }
}
